package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.media3.common.MediaItem
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode
import io.gitee.kotle.player.ui.getCountTimeByLong
import kotlinx.coroutines.CoroutineScope

class ExoPlayerCurrentMsText : AppCompatTextView, IExoPlayerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    init {
        setDefaultText()
    }


    override fun needPlayerListener(): Boolean {
        return true
    }

    private var config: ExoPlayerViewConfig<IExoPlayerMode>? = null
    override suspend fun onModelChange(
        scope: CoroutineScope,
        player: IPlayer<MediaItem, IExoPlayerMode>,
        oldModel: IExoPlayerMode?,
        newModel: IExoPlayerMode
    ) {
        super.onModelChange(scope, player, oldModel, newModel)
        setDefaultText()
    }

    private fun setDefaultText() {
        text = getCountTimeByLong(0)
    }

    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        this.config = config
        config.seekBarProgress.observeForever(::onSeekBarChange)
    }


    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
        this.config = null
        config.seekBarProgress.removeObserver(::onSeekBarChange)
    }

    private var enableSetText = true

    private fun onSeekBarChange(pair: Pair<Boolean, Float>?) {
        enableSetText = pair?.first ?: true
        pair?.second?.let {
            config?.player?.duration?.let { totalMs ->
                text = getCountTimeByLong((totalMs * it).toLong())
            }
        }
    }

    override suspend fun onTick(scope: CoroutineScope, player: IPlayer<MediaItem, IExoPlayerMode>) {
        super.onTick(scope, player)
        if (enableSetText) {
            text = getCountTimeByLong(player.currentPosition)
        }
    }
}